package com.aorise.controller.halt;

import com.aorise.exception.ServiceException;
import com.aorise.model.halt.*;
import com.aorise.service.halt.HaltService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;
import com.aorise.utils.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:cat
 * @Desicription: 计划停机控制器类
 * @Date:Created in 2019-06-11
 * @Modified By:
 */
@RestController
@Api(description ="计划停机信息接口")
public class HaltController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HaltService haltService;

    /**
     * 根据筛选条件进行分页查询停机记录信息
     * HTTP 方式：GET
     * API 路径：/api/halt/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllHaltListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "根据筛选条件进行分页查询停机记录信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询停机记录信息,提供计划停机管理-查询列表使用")
    @RequestMapping(value = "/api/halt/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllHaltListByPage(@ApiParam(value = "起始停机日期", required = false) @RequestParam(value = "startHaltTime", required = false) String startHaltTime,
                                         @ApiParam(value = "截止停机日期", required = false) @RequestParam(value = "endHaltTime", required = false) String endHaltTime,
                                         @ApiParam(value = "停机原因", required = false) @RequestParam(value = "reason", required = false) String reason,
                                         @ApiParam(value = "申请状态：1待审批，2通过，3驳回", required = false) @RequestParam(value = "status", required = false) Integer status,
                                         @ApiParam(value = "登录人ID", required = true) @RequestParam(value = "userId", required = true) Integer userId,
                                         @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                         @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getAllHaltListByPage");
        logger.debug("startHaltTime：" + startHaltTime);
        logger.debug("endHaltTime：" + endHaltTime);
        logger.debug("reason：" + reason);
        logger.debug("status：" + status);
        logger.debug("userId：" + userId);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startHaltTime", startHaltTime);
            map.put("endHaltTime", endHaltTime);
            map.put("reason", reason);
            map.put("status", status);
            map.put("userId", userId);
            map.put("isReadNo", ConstDefine.ISREAD_NO);
            map.put("isRead", ConstDefine.ISREAD);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<HaltModel> haltModels = haltService.getAllHaltListByPage(map, page);
            page.setList(haltModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:getAllHaltListByPage...msg:Get Halt List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:getAllHaltListByPage...msg:Get Halt List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 根据ID查询停机记录详情
     * HTTP 方式：GET
     * API 路径：/api/halt/id/{id}
     * 方法名：getHaltById
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "根据ID查询停机记录详情", httpMethod = "GET", response = String.class, notes = "根据ID查询停机记录详情，提供计划停机管理-查询停机记录详情使用")
    @RequestMapping(value = "/api/halt/id/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getHaltById(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                                   @ApiParam(value = "登录人ID", required = true) @RequestParam(value = "userId", required = true) Integer userId) {

        logger.debug("Request RESTful API:getHaltById");
        logger.debug("id" + id);
        logger.debug("userId" + userId);
        try {
            HaltModel haltModel = haltService.getHaltById(id,userId);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "",haltModel).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:getHaltById...msg:Get Halt By Id DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:getHaltById...msg:Get Halt By Id Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 新增停机记录信息
     * HTTP 方式：POST
     * API 路径：/api/halt
     * 方法名：addHalt
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "新增停机记录信息", httpMethod = "POST", response = String.class, notes = "新增停机记录信息，提供计划停机管理-创建申请使用")
    @RequestMapping(value = "/api/halt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String addHalt(@RequestBody @Validated HaltAddVO haltAddVO, BindingResult result) {

        logger.debug("Request RESTful API:addHalt");
        logger.debug("haltAddVO：" + haltAddVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            int ret = haltService.addHalt(haltAddVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:addHalt...msg:Add Halt DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (ServiceException e) {
            logger.error(
                    "controller:HaltController. function:addHalt...msg:Add Halt ServiceException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.CAMERA_NULL,
                    e.getMessage(), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:addHalt...msg:Add Halt Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 删除停机记录信息
     * HTTP 方式：DELETE
     * API 路径：/api/halt/id/{id}
     * 方法名：deleteHalt
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "删除停机记录信息", httpMethod = "DELETE", response = String.class, notes = "删除停机记录信息，提供计划停机管理-撤回计划停机申请使用")
    @RequestMapping(value = "/api/halt/id/{id}", method = RequestMethod.DELETE, produces = "application/json")
    public String deleteHalt(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                              @ApiParam(value = "修改人ID", required = true) @RequestParam(value = "editUser", required = true) Integer editUser) {
        logger.debug("Request RESTful API:deleteHalt");
        logger.debug("id" + id);
        logger.debug("editUser" + editUser);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("editUser", editUser);
            map.put("state", ConstDefine.STATE_DISABLE);
            map.put("id", id);
            int ret = haltService.deleteHalt(map);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:deleteHalt...msg:Delete Halt DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (ServiceException e) {
            logger.error(
                    "controller:HaltController. function:deleteHalt...msg:Delete Halt ServiceException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.APPLICATION_DELETE,
                    e.getMessage(), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:deleteHalt...msg:Delete Halt Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 查询停机记录未读消息总数
     * HTTP 方式：GET
     * API 路径：/api/halt/getHaltIsNotRead/userId/{userId}
     * 方法名：getHaltIsNotRead
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "查询停机记录未读消息总数", httpMethod = "GET", response = String.class, notes = "查询停机记录未读消息总数，提供导航上计划停机管理查询提醒数使用")
    @RequestMapping(value = "/api/halt/getHaltIsNotRead/userId/{userId}", method = RequestMethod.GET, produces = "application/json")
    public String getHaltIsNotRead(@ApiParam(value = "登录人ID", required = true) @PathVariable(value = "userId", required = true) Integer userId) {
        logger.debug("Request RESTful API:getHaltIsNotRead");
        logger.debug("userId" + userId);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            Long ret = haltService.getHaltIsNotRead(map);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:getHaltIsNotRead...msg:Get Halt Is Not Read DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:getHaltIsNotRead...msg:Get Halt Is Not Read Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 对停机记录信息点赞、取消赞
     * HTTP 方式：POST
     * API 路径：/api/halt/doLikeHalt
     * 方法名：doLikeHalt
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "对停机记录信息点赞、取消赞", httpMethod = "POST", response = String.class, notes = "对停机记录信息点赞、取消赞，提供计划停机管理-详情-点赞、取消赞使用")
    @RequestMapping(value = "/api/halt/doLikeHalt", method = RequestMethod.POST, produces = "application/json")
    public String doLikeHalt(@ApiParam(value = "停机记录ID", required = true) @RequestParam(value = "haltId", required = true) Integer haltId,
                             @ApiParam(value = "用户ID", required = true) @RequestParam(value = "userId", required = true) Integer userId) {
        logger.debug("Request RESTful API:doLikeHalt");
        logger.debug("haltId" + haltId);
        logger.debug("userId" + userId);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("haltId", haltId);
            map.put("userId", userId);
            int ret = haltService.doLikeHalt(map);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:doLikeHalt...msg:Do Like Halt DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:doLikeHalt...msg:Do Like Halt Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 新增停机记录评论信息
     * HTTP 方式：POST
     * API 路径：/api/halt/addHaltComment
     * 方法名：addHaltComment
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-11
     */
    @ApiOperation(value = "新增停机记录评论信息", httpMethod = "POST", response = String.class, notes = "新增停机记录信息，提供计划停机管理-详情-发表评论使用")
    @RequestMapping(value = "/api/halt/addHaltComment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String addHaltComment(@RequestBody @Validated HaltCommentAddVO haltCommentAddVO, BindingResult result) {

        logger.debug("Request RESTful API:addHaltComment");
        logger.debug("haltCommentAddVO：" + haltCommentAddVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            int ret = haltService.addHaltComment(haltCommentAddVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:addHaltComment...msg:Add Halt Comment DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:addHaltComment...msg:Add Halt Comment Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 根据条件分页查询停机设备
     * HTTP 方式：GET
     * API 路径：/api/halt/haltCamera/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getHaltCameraListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-12
     */
    @ApiOperation(value = "根据条件分页查询停机设备", httpMethod = "GET", response = String.class, notes = "根据条件分页查询停机设备,提供计划停机管理-停机设备列表-查询列表使用")
    @RequestMapping(value = "/api/halt/haltCamera/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getHaltCameraListByPage(@ApiParam(value = "设备编码", required = false) @RequestParam(value = "caNumber", required = false) String caNumber,
                                          @ApiParam(value = "设备名称", required = false) @RequestParam(value = "caName", required = false) String caName,
                                          @ApiParam(value = "设备类型：1,2,3", required = false) @RequestParam(value = "caType", required = false) Integer caType,
                                          @ApiParam(value = "设备品牌：1海康，2大华，3宇视", required = false) @RequestParam(value = "brand", required = false) Integer brand,
                                          @ApiParam(value = "起始停机日期", required = false) @RequestParam(value = "startHaltTime", required = false) String startHaltTime,
                                          @ApiParam(value = "截止停机日期", required = false) @RequestParam(value = "endHaltTime", required = false) String endHaltTime,
                                          @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                          @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getHaltCameraListByPage");
        logger.debug("caNumber：" + caNumber);
        logger.debug("caName：" + caName);
        logger.debug("caType：" + caType);
        logger.debug("brand：" + brand);
        logger.debug("startHaltTime：" + startHaltTime);
        logger.debug("endHaltTime：" + endHaltTime);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("caNumber", caNumber);
            map.put("caName", caName);
            map.put("caType", caType);
            map.put("brand", brand);
            map.put("startHaltTime", startHaltTime);
            map.put("endHaltTime", endHaltTime);
            map.put("halt", ConstDefine.HALT_YES);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<HaltCameraModel> haltCameraModels = haltService.getHaltCameraListByPage(map, page);
            page.setList(haltCameraModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:HaltController. function:getHaltCameraListByPage...msg:Get Halt Camera List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:HaltController. function:getHaltCameraListByPage...msg:Get Halt Camera List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

}
